const express = require('express');
const https = require('https');
const httpProxy = require('http-proxy');

const GL_PROXY_PORT = 13050;
const GL_GATEWAY_HOST = "http://gclife-gateway";
const GL_GATEWAY_PORT = 13000;

const cluster = require('cluster');
const os = require('os');
const CPUS = os.cpus().length;
if (cluster.isMaster) {
    for (var i = 0; i < CPUS; i++) {
        cluster.fork();
    }
}
else {
    const app = express();
    const proxy = httpProxy.createProxyServer();

    // 创建 HTTPS 服务器
    const fs = require('fs');
    const options = {
        key: fs.readFileSync('ssl/server.key', 'utf8'),
        cert: fs.readFileSync('ssl/server.crt', 'utf8')
    };
    const httpsServer = https.createServer(options, app);

    // 转发所有错误
    proxy.on('error', function (err, req, res) {
        res.end();
    });

    // 转发所有请求
    app.all('*', function (req, res) {
        proxy.web(req, res, {
            target: GL_GATEWAY_HOST + ":" + GL_GATEWAY_PORT
        });
    });

    // 启动代理服务器
    httpsServer.listen(GL_PROXY_PORT, function () {
        console.log('proxy server is running at %d', GL_PROXY_PORT);
    });
}
